<template>
  <div class="login-container">
    <h2 class="login-title">用户登录</h2>
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-width="80px"
      @keyup.enter="handleLogin"
    >
      <el-form-item label="用户名" prop="name">
        <el-input
          v-model="loginForm.name"
          placeholder="请输入用户名/邮箱"
          clearable
          :disabled="loading"
        >
          <template #prefix>
            <el-icon><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          show-password
          :disabled="loading"
        >
          <template #prefix>
            <el-icon><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item class="login-actions">
        <el-button
          type="primary"
          :loading="loading"
          @click="handleLogin"
        >
          登录
        </el-button>
        <el-button @click="resetForm" :disabled="loading">
          重置
        </el-button>
        <el-link type="primary" @click="gotoRegister" class="register-link">
          立即注册
        </el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios' // 导入 axios
import { initWebSocket } from '@/utils/websocket';
import { useContactStore } from '@/stores/contact';
 

const userStore = useUserStore()
const router = useRouter()

// 表单数据
const loginForm = ref({
  name: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  //  name: [
  //    { required: true, message: '请输入用户名', trigger: 'blur' },
  //    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  //  ],
  //  password: [
  //    { required: true, message: '请输入密码', trigger: 'blur' },
  //    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  //  ]
}

// 状态控制
const loading = ref(false)
const loginFormRef = ref(null)

// 登录处理
const handleLogin = async () => {
  try {
    // 表单验证
    await loginFormRef.value.validate()
    loading.value = true
    
    // 发送实际的 API 请求（假设后端接口是 /api/login）
    const response = await axios.post('/api/user/login', loginForm.value)
    if (response.data.code!== 200) { // 假设后端成功响应码是 200，根据实际情况调整
      throw new Error(response.data.message || '登录失败')
    }
    // 登录成功处理
    const { username, avatar } = response.data.data;
    userStore.login(response.data.data);

userStore.login(username, avatar, '123');
console.log('userStore after login:', userStore);
    
    const contactStore = useContactStore();

initWebSocket(response.data.data.tocken, (contacts) => {
  contactStore.setContacts(contacts);
});
console.log('contacts', contacts);


    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  loginFormRef.value.resetFields()
}

// 跳转注册
const gotoRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  width: 400px;
  margin: 100px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}

.login-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.register-link {
  margin-left: auto;
}
</style>